package com.xinyu.service.impl;

import com.xinyu.service.IAAngleProfileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

@Service
public class AAngleProfileServiceImpl implements IAAngleProfileService {

    public List<List<Integer>> processExcelFile(MultipartFile file) {
        List<List<Double>> calculatedData = calculateData(file);
        List<List<Double>> rotatedData = rotate180(calculatedData);
        return groupAndLabelData(rotatedData);
    }

    private List<List<Double>> calculateData(MultipartFile file) {
        List<List<Double>> result = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
            // 读取标题行
            String headerLine = reader.readLine();
            if (headerLine == null) return result;

            String[] headers = headerLine.split(",");

            // 定位关键列索引
            int cup7_1Index = findColumnIndex(headers, "cup7-1");
            int cup7_2Index = findColumnIndex(headers, "cup7-2");
            int cup7_3Index = findColumnIndex(headers, "cup7-3");

            // 预计算其他cup组的列索引
            Map<Integer, List<Integer>> cupGroups = new LinkedHashMap<>();
            for (int group = 1; group <= 13; group++) {
                if (group == 7) continue;

                List<Integer> cols = new ArrayList<>();
                cols.add(findColumnIndex(headers, "cup" + group + "-1"));
                cols.add(findColumnIndex(headers, "cup" + group + "-2"));
                cols.add(findColumnIndex(headers, "cup" + group + "-3"));
                cupGroups.put(group, cols);
            }

            // 处理数据行
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) continue;

                String[] values = line.split(",");
                List<Double> newRow = new ArrayList<>();

                // 1. 添加cup7-1到最左
                newRow.add(parseDouble(values[cup7_1Index]));

                // 2. 添加前6组cup的和
                for (int group = 1; group <= 6; group++) {
                    newRow.add(sumGroup(values, cupGroups.get(group)));
                }

                // 3. 添加cup7-2到中间
                newRow.add(parseDouble(values[cup7_2Index]));

                // 4. 添加后6组cup的和
                for (int group = 8; group <= 13; group++) {
                    newRow.add(sumGroup(values, cupGroups.get(group)));
                }

                // 5. 添加cup7-3到最右
                newRow.add(parseDouble(values[cup7_3Index]));

                result.add(newRow);
            }
        } catch (Exception e) {
            throw new RuntimeException("CSV处理失败", e);
        }

        return result;
    }

    private double parseDouble(String value) {
        try {
            return Double.parseDouble(value.trim());
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }

    private double sumGroup(String[] values, List<Integer> columnIndices) {
        double sum = 0;
        for (int col : columnIndices) {
            sum += parseDouble(values[col]);
        }
        return sum;
    }

    private int findColumnIndex(String[] headers, String columnName) {
        for (int i = 0; i < headers.length; i++) {
            if (columnName.equalsIgnoreCase(headers[i].trim())) {
                return i;
            }
        }
        throw new IllegalArgumentException("列未找到: " + columnName);
    }

    private List<List<Double>> rotate90(List<List<Double>> data) {
        if (data.isEmpty()) {
            return new ArrayList<>();
        }

        int originalRows = data.size();
        int originalCols = data.get(0).size();

        // 旋转90度后的矩阵将是 originalCols x originalRows
        List<List<Double>> rotated = new ArrayList<>(originalCols);

        // 从最后一列开始，向前遍历
        for (int col = originalCols - 1; col >= 0; col--) {
            List<Double> newRow = new ArrayList<>(originalRows);

            // 从上到下遍历行
            for (int row = 0; row < originalRows; row++) {
                newRow.add(data.get(row).get(col));
            }

            rotated.add(newRow);
        }

        return rotated;
    }
    private List<List<Double>> rotate180(List<List<Double>> data) {
        List<List<Double>> rotated = new ArrayList<>();

        // 行逆序
        for (int i = data.size() - 1; i >= 0; i--) {
            List<Double> originalRow = data.get(i);
            List<Double> newRow = new ArrayList<>();

            // 元素逆序
            for (int j = originalRow.size() - 1; j >= 0; j--) {
                newRow.add(originalRow.get(j));
            }

            rotated.add(newRow);
        }

        return rotated;
    }

    private List<List<Integer>> groupAndLabelData(List<List<Double>> data) {
        // 1. Collect all unique values and sort them
        Set<Double> uniqueValues = new TreeSet<>();
        for (List<Double> row : data) {
            uniqueValues.addAll(row);
        }
        List<Double> sortedValues = new ArrayList<>(uniqueValues);

        // 2. Calculate group boundaries (14 groups)
        int totalGroups = 9;
        double[] thresholds = new double[totalGroups];
        int valuesPerGroup = (int) Math.ceil((double) sortedValues.size() / totalGroups);

        for (int i = 0; i < totalGroups; i++) {
            int index = Math.min(i * valuesPerGroup, sortedValues.size() - 1);
            thresholds[i] = sortedValues.get(index);
        }
        thresholds[totalGroups - 1] = Double.MAX_VALUE; // Ensure all values are covered

        // 3. Create value to group mapping
        Map<Double, Integer> valueToGroupMap = new HashMap<>();
        int currentGroup = 0;
        for (Double value : sortedValues) {
            while (value >= thresholds[currentGroup + 1] && currentGroup < totalGroups - 1) {
                currentGroup++;
            }
            valueToGroupMap.put(value, currentGroup);
        }

        // 4. Transform original data to group numbers
        List<List<Integer>> result = new ArrayList<>();
        for (List<Double> row : data) {
            List<Integer> newRow = new ArrayList<>();
            for (Double value : row) {
                newRow.add(valueToGroupMap.get(value));
            }
            result.add(newRow);
        }

        return result;
    }
}